<?php

namespace App\Services;

use App\SysLog;
use DB;
use App\Project;
use App\User;
use Illuminate\Support\Facades\Log;

class LogService
{
    const LOG_LEVEL_DEBUG = 'DEBUG';
    const LOG_LEVEL_INFO = 'INFO';
    const LOG_LEVEL_WARN = 'WARN';
    const LOG_LEVEL_ERROR = 'ERROR';

    const ACCESS_LEVEL_USER_EVENT = 0;
    const ACCESS_LEVEL_SYSTEM_EVENT = 100;

    public function __construct()
    {
    }

    public function info($actionType, $remarks, User $user = null, Project $application = null)
    {
        $this->logUserEvent(self::LOG_LEVEL_INFO, $actionType, $remarks, $user, $application);
    }

    public function sinfo($actionType, $remarks, User $user = null, Project $application = null)
    {
        $this->logSystemEvent(self::LOG_LEVEL_INFO, $actionType, $remarks, $user, $application);
    }

    public function logUserEvent($level, $actionType, $remarks, User $user = null, Project $application = null)
    {
        $this->log($level, self::ACCESS_LEVEL_USER_EVENT, $actionType, $remarks, $user, $application);
    }

    public function logSystemEvent($level, $actionType, $remarks, User $user = null, Project $application = null)
    {
        $this->log($level, self::ACCESS_LEVEL_SYSTEM_EVENT, $actionType, $remarks, $user, $application);
    }

    public function log($level, $accessLevel, $actionType, $remarks, User $user = null, Project $application = null)
    {
        $record = new SysLog;
        $record->level = $level;
        $record->access_level = $accessLevel;
        if ($user) {
            $record->user_id = $user->id;
            $record->user_role = $user->getRoleDisplayText();
            $record->user_name = $user->name;
            $record->user_org_name = $user->work_org_name;
        }
        if ($application) {
            $awardSvc = new AwardService;
            $record->application_id = $application->id;
            $record->award_id = $application->award_id;
            $record->award_name = $awardSvc->getAwardInfo($application->award_id)['name'];
        }
        $record->action_type = $actionType;
        $record->description = $remarks;
        $record->save();
    }

}